package org.example.wikwok.service.impl;

import org.example.wikwok.common.ReturnedMessage;
import org.example.wikwok.mapper.*;
import org.example.wikwok.pojo.OperationLog;
import org.example.wikwok.pojo.Video;
import org.example.wikwok.pojo.VideoInfo;
import org.example.wikwok.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//实现视频搜索功能，基于关键词搜索视频。
@Service
public class SearchServiceImpl implements SearchService {
@Autowired
private VideoMapper videoMapper;
@Autowired
private LikeMapper likeMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private CommentMapper commentMapper;
@Autowired
private Secondary_CommentMapper secondary_commentMapper;
@Autowired
private CollectMapper collectMapper;
@Autowired
private OperationLogMapper operationLogMapper;
    @Override
    public List<VideoInfo> search(int userId, String keyword) {
        try{
            // 调用 VideoMapper 的 search 方法，传入 userId 和 keyword，返回搜索结果。
            List<Video>videos=videoMapper.selectByTitleOrDescription(keyword);
            List<VideoInfo> videoInfoList=new ArrayList<>();
            for(Video video:videos){
                videoInfoList.add(new VideoInfo(video,likeMapper.selectCountByVideoId(video.getId()),collectMapper.selectCountByVideoId(video.getId()),commentMapper.selectCountByVideoId(video.getId())+secondary_commentMapper.selectByVideoId(video.getId()),userMapper.selectByPrimaryKey(video.getUploaderid())));
            }
            operationLogMapper.insert(OperationLog.build("User search in video ", userId, keyword+"_"+ReturnedMessage.SEARCHEDSUCCESS));
            return videoInfoList;
        }catch(Exception e){
            operationLogMapper.insert(OperationLog.build("User search in video ", userId, keyword+"_"+ReturnedMessage.SEARCHEDFAILED));
            return null;
        }
    }
}
